package com.itwang.thread;

import com.itwang.common.*;
import com.itwang.handler.ConsumerException;

import java.io.IOException;

public class IpWatchThread implements Runnable {
	private static  long SLEEP_TIME;//线程睡眠时间,单位ms
	private static String SERVICE_NAME;
	static {
		SERVICE_NAME = PropertiesUtil.getKey("serviceName");
		SLEEP_TIME = Long.valueOf(PropertiesUtil.getKey("threadCheckIpTime"));
	}
	
	public void run() {
		//初始化当前ip地址
		String ips = "";
		Logger.info("初始化程序");
		
		Boolean enableUseIpFile = Boolean.valueOf(PropertiesUtil.getKey("enableUseIpFile"));
		try {
			//如果使用ip硬盘文件,则程序会读取硬盘文件与当前ip做比对,
			//如果不使用存储ip的硬盘文件,则程序每次启动都会向邮箱发送邮件.
			if (enableUseIpFile){
				ips = FileUtil.getIpFile();
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		while (true) {
			//获取到最新的ip地址
			String localIpAString = IpGeter.getLocalIpAString();
			
			//如果ip相等,结束进程,否则更新ips内容,并且将最新ip写入到文件中,并向指定邮箱发送最新ip邮件
			//需要保持ips和文件中的ip相同
			if (ips.equals(localIpAString)) {
				//线程睡眠
				Logger.info("IP未发生改变");
				try {
					Thread.sleep(SLEEP_TIME);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}else {
				//更新当前ip
				ips = localIpAString;
				Logger.keyInfo("IP已经发生改变");
				Logger.keyInfo("最新IP为:"+localIpAString);
				//发送邮件
				Logger.info("发送最新IP邮件到"+PropertiesUtil.getKey("harvestEmail"));
				try {
					SendEmail.sendMessage(SERVICE_NAME + "<br>" +localIpAString);
				} catch (Exception e) {
					//一旦邮件发送失败则清空本地存储的ip地址
					//为了防止在,在邮件可以发送的时候继续发送.
					localIpAString = "";
					throw new ConsumerException(e);
				}
				
				//将最新ip写入文件
				Logger.info("向磁盘更新最新IP");
				try {
					FileUtil.setIpFile(localIpAString);
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				//线程睡眠
				// Logger.info("线程休眠"+ SLEEP_TIME / 1000 + "秒");
				try {
					Thread.sleep(SLEEP_TIME);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
		}

	}
}
